<template>
    <div>
        <el-form :model="updateRole" ref="roleForm" label-width="100px" label-position="right" style="width:400px"
            :rules="rules">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="updateRole.name" aria-placeholder="请输入角色名称">
                </el-input>
            </el-form-item>

        </el-form>
        <el-tree style="max-width:600px" :data="authList" show-checkbox node-key="index" :default-expand-all="true"
            :default-checked-keys="checkedKeys" @check-change="handleCheckChange">
        </el-tree>
    </div>
</template>
<script setup lang="ts">
import type { roleInfoData } from '@/api/role/type';
import type { FormRules } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
//引入菜单项对象数组
import menuList from '@/config/menuConfig';

//接受父组件传递过来的要编辑的角色对象
const props = defineProps(["role"]);



let updateRole = ref<roleInfoData>({
    name: ''
});
//表达校验规则
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入角色名称', trigger: "blur" }],
});
// 树形控件数据数组
const authList = ref([])
//树形控件所有选中项的数组
const checkedKeys = ref<string[]>([])
//处理树形控件元素对象
const getAuthNodes = (menuList: any) => {
    return menuList.map((item: any) => {
        if (!item.children) {
            return {
                index: item.index,
                label: item.title
            }
        } else {
            return {
                index: item.index,
                label: item.title,
                children: getAuthNodes(item.children)
            }
        }
    })
}

interface Tree {
    index: string
}
//树形控件选择回调
const handleCheckChange = (
    data: Tree,
    checked: boolean,
    //@ts-ignore
    indeterminate: boolean
) => {
    // const index = checkedKeys.value.indexOf(data.index);
    // if (checked && index === -1) {
    //     checkedKeys.value.push(data.index); // 勾选：添加
    // } else if (!checked && index !== -1) {
    //     checkedKeys.value.splice(index, 1); // 取消勾选：删除
    // }
    if (checked) {
        if (checkedKeys.value.indexOf(data.index) == -1) {
            checkedKeys.value.push(data.index)
        }
    }else {
        if (checkedKeys.value.indexOf(data.index) != -1) {
            checkedKeys.value.splice(checkedKeys.value.indexOf(data.index), 1)
        }

    }
};

//为父元素提供数据方法
const getMenus = () => {
    updateRole.value.menus = checkedKeys.value;
    return updateRole.value
}
//对外暴露
defineExpose({
    getMenus
})
onMounted(() => {
    updateRole.value = { ...props.role };
    authList.value = getAuthNodes(menuList)
    checkedKeys.value = [...props.role.menus];
})


</script>

<style scoped></style>